<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>day241128-chat-demo</title>

    <style>
         * {
           margin: 0;
           padding: 0;
         }

         html, body {
           height: 100%;
           background-color: #f5f5f5;
         }

         .chat-history {
             border: 1px solid darkred;
             height: 300px;
             /*让聊天记录界面放满剩余空间*/
             flex-grow: 1;
             padding: 16px;
             overflow-y: auto;
         }

         .input-container {
             border: 1px solid darkgreen;
             padding: 16px;
             display: flex;
             justify-content: space-between;
         }

         .chat-container {
             height: 100vh;
             display: flex;
             flex-direction: column;
             justify-content: space-between;
         }
         /*#是找id*/
         #message-input {
             flex-grow: 1;
             padding: 8px;
         }
         #send-button {
             margin-left: 8px;
             padding: 8px 16px;
         }


         .message {
             margin-bottom: 15px;
             display: flex;
         }
         .message-content {
             padding: 10px 15px;
             border-radius: 15px;
             max-width: 70%;
         }

         .user-message {
             justify-content: flex-end;
         }

         .ai-message {
             justify-content: flex-start;
         }

         .user-message .message-content {
             background: #007bff;
             color: white;
         }
         .ai-message .message-content {
             background: #e9ecef;
             color: black;
         }
    </style>
</head>
<body>
<div class="chat-container">
  <div class="chat-history" id="chat-history">
    <!-- 聊天记录将显示在这里 -->
  </div>
  <div class="input-container">
    <input type="text" id="message-input" placeholder="输入消息...">
    <button id="send-button">发送</button>
  </div>
</div>

<script src="jquery.min.js"></script>

<script>
    const chatHistory = document.getElementById('chat-history');
    const messageInput = document.getElementById('message-input');
    const sendButton = document.getElementById('send-button');
    sendButton.addEventListener('click', send);
    //回车发送
    messageInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            send();
        }
    });

    function send() {
        // 去除前后空格trim
        const message = messageInput.value.trim();
        // alert(message)弹窗
        if(message) {
            addMessage(message);
            messageInput.value = '';
            // 模拟AI的响应
            // setTimeout(() => {
            //     addMessage("来自AI的响应：" + message, true);
            // }, 1000);

            getStreamResponse(message);
        }
    }

    function getResponseFromServer(message){
        // let xhr;
        // if (window.XMLHttpRequest) {
        //     xhr = new XMLHttpRequest();
        // } else {
        //     xhr = new ActiveXObject("Microsoft.XMLHTTP");
        // }
        // xhr.onreadystatechange = function () {
        //     if (xhr.readyState === 4 && xhr.status === 200) {
        //         addMessage(xhr.responseText, true);
        //     }
        // }
        // xhr.open("GET", "/ai/chat?message="+ message, true);
        // xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        // xhr.send();
        $.get("/ai/chat", {message: message}, function(resp) {
            addMessage(resp, true)
        });
    }

    function addMessage(content, isAI = false) {
        const messageDiv = document.createElement('div');
        // messageDiv.className = `message`;
        messageDiv.className = `message ${isAI ? 'ai-message' : 'user-message'}`;

        const messageContent = document.createElement('div');
        messageContent.className = 'message-content';
        messageContent.textContent = content;

        messageDiv.appendChild(messageContent);
        chatHistory.appendChild(messageDiv);
        // 滚动到最新消息
        chatHistory.scrollTop = chatHistory.scrollHeight;

        return messageContent;

    }

    function getStreamResponse(message) {
        // 创建AI消息占位符
        const aiMessageContent = addMessage('', true);

        // 创建EventSource连接
        const eventSource = new EventSource(`/ai/chat-stream?prompt=${encodeURIComponent(message)}`);

        // 用于累积接收到的内容
        let accumulatedContent = '';

        // 处理接收到的消息
        eventSource.onmessage = function(event) {
            accumulatedContent += event.data;
            aiMessageContent.textContent = accumulatedContent;
            chatHistory.scrollTop = chatHistory.scrollHeight;
        };

        // 处理错误
        eventSource.onerror = function(error) {
            eventSource.close();
            if (accumulatedContent === '') {
                aiMessageContent.textContent = '抱歉，发生错误了';
            }
        };
    }
</script>

</body>
</html>